/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {_Input,_Button,_Icon,_Modal} from 'ANT_DE';
const Input = _Input,
    Icon = _Icon, Modal = _Modal;

import {message} from 'antd';
import {Button} from 'fly';
import SavePackStepMutation from '../mutation/SavePackStep';  //保存

import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import GetQiNiuToken from "../mutation/GetQiNiuTokenMutation"  //上传图片获取token

import GetPackStepInfo from '../mutation/GetPackStepInfoMutation'
import '../css/packStep.css';

// 细分组件
import {Header,PackList,ViewImgList,ViewAAddImg} from '../components/PackStep_Header';

import AddImgModal from "../components/AddImgModal";  //上传图片
import FileUpData from '../components/FileUpDataPro'  //上传附件

import Config from "../../../../util/Config"

/*
 * 包装步骤  展示层 sds
 * */

function PackStepView (props){
    const data = props.data;
    return (<div>
            包装步骤展示层
        </div>
    )
}

/*导出组件*/
export default class PackStep extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            fileList:[],   //上傳文件列表
            previewImage: '',
            previewVisible:false,  //图片预览
            token:"",

            fileUpdataList:[],  //上传附件的list
            picRemoveList:[],
            dis_btn:false
        };

        this.FixedImgSrc = Config.qiuniu;

        this.handlePreview = this.handlePreview.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.save = this.save.bind(this);

        this.handleChangeText = this.handleChangeText.bind(this);

        this.picRemove = this.picRemove.bind(this);
        this.beforeUpload = this.beforeUpload.bind(this);

        this.addImg = this.addImg.bind(this);

        this.addImg = this.addImg.bind(this);
        this.addFileImg = this.addFileImg.bind(this);

        this.addFileItem = this.addFileItem.bind(this); //上传文件 更新内部状态list
    }

    componentWillMount(){
        // 获得
        this.pdId = this.props.pdId;

        // 获得上次保存的数据
        // GetPackStepInfo
        Relay.Store.commitUpdate(new GetPackStepInfo({
                pdId:this.pdId
            }),{
                onSuccess:(res)=>{
                    let data = res.getPackStepInfo.getPackStepInfo;
                    if(data.errorCode == 0){

                        let con_img = data.packStep,
                            com_file = data.packStep,
                            arr = [],arr_1 = [];

                        (!con_img) ? arr = [] : arr = JSON.parse(con_img.imgJson);
                        (!com_file) ? arr_1 = [] : arr_1 = JSON.parse(com_file.fileJson);

                        this.setState({
                            fileList:arr,
                            fileUpdataList:arr_1
                        })
                    }else if(data.errorCode == 500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );

        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        })
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败 ")
                }
            }
        );
    }

    componentDidMount(){}


    //  验证格式需要通过obj传递到另一个组件调用，必须要在当前proto原型上，不可添加到自由属性.
    accept = ".jpg,.png,.gif,.jpeg,.bmp";
    fileAccept = ".pdf,.xlsx,.xls,.docx,.doc";

    getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    /*文本输入change*/
    handleChangeText = (e,index)=>{
        this.state.stepArr[index].value = e.target.value;
        this.setState({
            stepArr:this.state.stepArr
        });
    };

    // 删除图片
    picRemove(index){
        //下列固定为0，因为list最多只能上传一个，固0
        const Rn =  this.state.fileList[index].file.response.key;
        //过渡动画
        this.state.fileList[index].file.__transClass = "leave";
        // 伪更新
        this.setState({ fileList:this.state.fileList });
        // 记录删除操作;
        this.state.picRemoveList.push(Rn);
        setTimeout(()=>{
            this.state.fileList.splice(index,1);
            this.setState({
                fileList:this.state.fileList
            })
        },300)
    }

    //sadsdsd

    save(){
        let fileList = this.state.fileList,
            F = this.state.fileUpdataList;

        // 锁定disabled
        this.setState({dis_btn:true});

        // 筛选文是否为 uploading
        for(let key in F){
            if(F[key].status === "uploading"){
                message.info("文件正在上传中");
                this.setState({dis_btn:false})
                return false
            }
        }


        Relay.Store.commitUpdate(
            new SavePackStepMutation({
                pdId:this.pdId,
                imgJson:JSON.stringify(fileList),
                fileJson:JSON.stringify(F),
            }), {
                onFailure: (err) => {
                    message.error("网络请求失败");
                },
                onSuccess: (res)=> {
                    const L = res.savePackStep.savePackStep;
                    setTimeout(()=>{
                        if(L.errorCode == 0){
                            this.setState({dis_btn:false});
                            message.success("保存成功");
                        }else if(L.errorCode == 500){
                            message.error(" 服务器错误，请联系管理员")
                        }
                    },500)
                }
            }
        );


        let R = this.state.picRemoveList;

        if(R.length === 0 ){ return; }

        // 删除图片;
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey:R.join(",")
            }),
            {
                onFailure: () => {
                    message.error("")
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        this.setState({picRemoveList:[]});
                    }else if(errorCode == 500){
                        message.error("服务器错误，请联系管理员")
                    }
                }
            }
        )
    }

    // 预览图片关闭
    handleCancel = ()=>{
        this.setState({
            previewVisible:false,
        });
        // 优化用户体验，延时一秒清空图片
        setTimeout(()=>{
            this.setState({
                previewImage:""
            })
        },700);
    };

    // 上传之前进行验证
    beforeUpload(file){

        const MaxSize = 8;  //最大限度 8M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }

    //附件上传之前验证
    fileBeforeload(file){
        const MaxSize = 10;  //最大限度 10M;

        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("文件大小超过限制");
            return false;
        }
    }

    // 预览图片
    handlePreview = (index) => {
        this.setState({
            previewVisible:true,
            previewImage:this.FixedImgSrc + this.state.fileList[index].file.response.key
        })
    };

    // 添加图片
    addImg(){
        if(this.state.fileList.length < 20){
            this.refs.addFileImgModal.setState({
                visible:true,
                text:"",
                imgSrc:"",
                fileList:[],
                left:0,
                top:0,
                alarm:false,
                showLoading:false
            });
        }else{
            message.error("图片最多上传20张，您已超过上限")
        }
    }

    fileBeforeload(e){
        let Reg = [".xlsx",".xls", ".PDF", ".docx", ".doc"];  //格式
        function formatTest(reg,name){
            if(!reg || !name){ return; }
            const D = Array.from(reg),
                N = name.toLowerCase();
            for(let i in D){
                const I = D[i].toLowerCase();
                if(N.lastIndexOf(I) !== -1){
                    return true
                }
            }
            return false;
        }
        if(!!e.name){
            if(formatTest(Reg,e.name)) {
                return true
            }else{
                message.error("文件格式错误，请重新选择");
                return false;
            }
        }
    }

    //上传图片配置
    uploadPlugin = {
        className:"packagSteps_updata",
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeUpload,
        listType:"picture-card",
        accept:this.accept,
    };

    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        accept:this.fileAccept,
        maxlength:5
    };

    // 新增图片函数  (push 到当前组件)
    addFileImg({file,text}){
        if(this.state.fileList.length < 20) {
            if (file) {
                this.state.fileList.push({file,text});
                this.setState({
                    fileList: this.state.fileList
                })
            }
        }else{
            message.error("最多只可上传20张");
        }
    }

    // 新增文件函数，（push 当前组件）
    addFileItem(fileList){
        this.state.fileUpdataList = fileList;
        this.setState({
            fileUpdataList:this.state.fileUpdataList
        })
    }

    handleClickSelf(){
        message.warning("附件最多允许上传5个")
    }

    //asd
    render(){
        const {dis_btn,previewVisible, previewImage, fileList,token,fileUpdataList} = this.state,
            {} = this.props;


        return (
            <div className="poduction_manage_tab_box" >
                <div className="product_packagSteps">

                    {/*附件 列表*/}
                    <FileUpData
                        className="packagSteps_updataFile"
                        filePlugin={this.fileUploadPlugin}
                        fileList={fileUpdataList}
                        callBack={this.addFileItem}   //回调，第一个参数为file,第二个参数为本地name
                        token={token}
                        isShowTrigger={fileUpdataList.length < this.fileUploadPlugin.maxlength}
                        handleClickSelf={this.handleClickSelf}
                    />

                    <div className="product_packagSteps-upload">
                        {/*图片展示系列表*/}
                        {
                            fileList.length !== 0 && fileList.map((item,index)=>
                                <ViewImgList
                                    key={item.file.uid}
                                    imgSrc={`${this.FixedImgSrc + item.file.response.key}`}
                                    imgName={item.file.name}
                                    handlePreview={(e)=>this.handlePreview(index)}
                                    handleRemove={(e)=>this.picRemove(index)}
                                    textValue={item.text}
                                    transClass={item.file.__transClass}   //过渡动画类，中途插入
                                />
                            )
                        }

                        {/*添加图片模版*/}
                        {
                            fileList.length<20 &&
                            <ViewAAddImg  onClick={this.addImg} />
                        }

                        {/*预览图片*/}
                        <Modal className="production_preview" visible={previewVisible} footer={null} width={800} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>

                        {/*添加图片弹出框*/}
                        <AddImgModal
                            uploadPlugin = {this.uploadPlugin}   //上传参数配置
                            ref="addFileImgModal"   //ref方便visible显示
                            token={token}   // 上传图片时，必须的token，(此token异步返回)
                            addFileImg={this.addFileImg}   //上传成功的回调，第一个参数的第一个属性为返回的fill,第二个属性为text描述
                            //  text 描述 props配置信息
                            TextProps={{  className:"packagSteps_AddImgModal_textArea",
                                rows:3,
                                placeholder:"请输入描述信息"
                            }}
                            limit={{width:500,height:500}} //最小宽高限制参数
                        />
                    </div>

                    <div className="packagSteps_footer">
                        <Button type="primary" onClick={this.save} loading={dis_btn} disabled={dis_btn}> 保存 </Button>
                    </div>
                </div>
            </div>
        )
    }
}